package com.qianxun.module.base.view;

import com.qianxun.plugins.log.LogPoint;
import com.qianxun.plugins.shiro.LoginExceptionManager;
import com.qianxun.plugins.shiro.LoginTypeToken;
import com.qianxun.plugins.shiro.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: huwei
 * @date: 2019/9/12 17:03
 * @version: 1.3.0
 */
@Slf4j
@Controller
public abstract class BaseLoginViewController extends BaseViewController {

    @LogPoint(key = "login" ,notes = "${username}登录系统")
    @PostMapping(value = {"/login"})
    public ModelAndView login(ModelAndView modelAndView , String username , String password , HttpServletRequest request , HttpServletResponse response){
        LoginTypeToken usernamePasswordToken = getCustomShiroToken(username, password);
        try {
            SecurityUtils.getSubject().login(usernamePasswordToken);
            //重定向到主页
            modelAndView.setViewName("redirect:".concat("index.html"));
        }catch (Throwable e) {
            toLogin(modelAndView ,LoginExceptionManager.errorMsg(e) ,request ,response);
        }
        return modelAndView;
    }

    @LogPoint(key = "toLogin" ,notes = "去到登录页面")
    @RequestMapping(value = {"/toLogin"})
    public ModelAndView toLogin(ModelAndView modelAndView ,String msg, HttpServletRequest request , HttpServletResponse response){
        modelAndView.setViewName(prefix().concat("/login.html"));
        modelAndView.addObject("msg" ,msg);
        return modelAndView;
    }

    @RequestMapping(value = {"/logout"})
    public ModelAndView logout(ModelAndView modelAndView, HttpServletRequest request , HttpServletResponse response) {
        modelAndView.setViewName("redirect:toLogin");
        modelAndView.addObject("msg","已退出");
        ShiroUtil.getSubject().logout();
        return modelAndView;
    }

    /**
     * 获取一个token对象
     * @param username 用户名
     * @param password 密码
     * @return
     */
    protected abstract LoginTypeToken getCustomShiroToken(String username , String password);
}
